﻿using DotNet4.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace BaiduYun
{
    internal class BaiduYunGroup
    {
        public struct ShortInfo
        {
            public string name, usercount, shortUrl;
        }

        /// <summary>
        /// 取贴吧帖子中所有ShortUrl
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string[] GetTiebaShort(string p)
        {
            //Console.WriteLine(p);
            List<string> list = new List<string>();
            //html = "http://pan.baidu.com/mbox/homepage?short=1234";
            int pn = 0, maxPage = 1;
            HttpHelper http = new HttpHelper();
            var head = new System.Net.WebHeaderCollection(); head.Add(System.Net.HttpRequestHeader.AcceptEncoding, "gzip, deflate, sdch");
            while (true)
            {
                pn++;
                HttpItem item = new HttpItem
                {
                    URL = "http://tieba.baidu.com/p/" + p + "?pn=" + pn,
                    Header = head,
                    //ProxyIp = "127.0.0.1:8888",
                    //Accept-Encoding: gzip, deflate, sdch
                };

                HttpResult res = http.GetHtml(item);
                if (pn == 1)
                {
                    Match mMaxPage = Regex.Match(res.Html, "共<span class=\"red\">([0-9]*?)</span>页");
                    if (mMaxPage.Success) maxPage = Convert.ToInt32(mMaxPage.Groups[1].Value);
                }

                MatchCollection m = Regex.Matches(res.Html, "pan.baidu.com/mbox/homepage\\?short=([a-zA-Z0-9]{7})");
                for (int i = 0; i < m.Count; i++)
                {
                    list.Add(m[i].Groups[1].Value);
                    //Console.WriteLine(m[i].Groups[0].Value);
                }

                if (pn >= maxPage) break;
            }

            //return list.ToArray();

            return list.Distinct().ToList().ToArray();
        }

        public static IOrderedEnumerable<KeyValuePair<string, int>> GetTiebaTimes(int n)
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            for (int i = 0; i < n; i++)
            {
                HttpItem item = new HttpItem
                {
                    URL = "http://tieba.baidu.com/f/search/res?isnew=1&kw=&qw=homepage%3Fshort&rn=10&un=&only_thread=0&sm=1&sd=&ed=&pn=" + (i + 1),
                };
                HttpHelper http = new HttpHelper();
                HttpResult res = http.GetHtml(item);
                MatchCollection m = Regex.Matches(res.Html, "贴吧：<a class=.*?<font class=\"p_violet\">(.+?)</font></a>");
                for (int j = 0; j < m.Count; j++)
                {
                    string tb = m[j].Groups[1].Value;
                    if (dic.ContainsKey(tb))
                    {
                        dic[tb]++;
                    }
                    else
                    {
                        dic.Add(tb, 1);
                    }
                }
            }

            //List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>();
            IOrderedEnumerable<KeyValuePair<string, int>> list = dic.OrderByDescending(s => s.Value);
            //foreach (var item in list)
            //{
            //    Console.WriteLine("{0}, {1}", item.Key, item.Value);
            //}

            return list;
        }

        /// <summary>
        /// 获取贴吧帖子url
        /// </summary>
        /// <param name="tb"></param>
        /// <returns></returns>
        public static string[] GetTiebaUrl(string tb)
        {
            var head = new System.Net.WebHeaderCollection(); head.Add(System.Net.HttpRequestHeader.AcceptEncoding, "gzip, deflate, sdch");
            HttpItem item = new HttpItem
            {
                URL = "http://tieba.baidu.com/f?kw=" + Uri.EscapeDataString(tb),
                Header = head,
            };
            HttpHelper http = new HttpHelper();
            HttpResult res = http.GetHtml(item);
            //MatchCollection m = Regex.Matches(res.Html, @"(http://pan.baidu.com/mbox/homepage\?short=.*?)<");
            MatchCollection m = Regex.Matches(res.Html, "<a href=\"/p/([0-9]*?)\"");

            //for (int i = 0; i < m.Count; i++)
            //{
            //    Console.WriteLine(m[i].Groups[1].Value);
            //}

            string[] url = new string[m.Count];
            for (int i = 0; i < m.Count; i++)
            {
                url[i] = m[i].Groups[1].Value;
                //Console.WriteLine(url[i]);
            }
            return url;
        }

        /// <summary>
        /// 加入群组
        /// </summary>
        /// <param name="sh"></param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static bool Join(string sh, string cookie)
        {
            var err = IsShortUse(sh);
            if (err == null) return false;
            HttpItem item = new HttpItem()
            {
                URL = string.Format("http://pan.baidu.com/mbox/group/join?from_referrer=%2F&short={0}&t=1455251845607&bdstoken=&channel=chunlei&clienttype=0&web=1&app_id=250528",
                sh),
                Cookie = cookie,
            };
            HttpHelper http = new HttpHelper();
            HttpResult res = http.GetHtml(item);
            //Console.WriteLine(res.Html);
            // 2158 网络错误 多次尝试
            if (res.Html.IndexOf("errno\":0") != -1)
            {
                return true;
            }
            else
            {
                Console.WriteLine(string.Format("{0}, {1}, {2}", "Join errno != 0", sh, res.Html.Trim()));
                return false;
            }
        }

        public static string Login(string user, string pwd)
        {
            string pd = string.Format("_client_id={0}&_client_type=2&_client_version=4.5.1&from=tieba&ka=open&net_type=1&passwd={1}&un={2}",
                _GetCid(),
                Uri.EscapeDataString(Convert.ToBase64String(Encoding.Default.GetBytes(pwd))),
                HttpUtility.UrlEncode(user));
            string sign = _GetSign(pd);
            pd = pd + "&sign=" + sign;
            //Console.WriteLine(pd);
            HttpItem item = new HttpItem
            {
                URL = "http://c.tieba.baidu.com/c/s/login",
                Postdata = pd,
                //body ＝ “_client_id=” ＋ _Login_GetCid () ＋ “&_client_type=2&_client_version=4.5.1&from=tieba&ka=open&net_type=1&passwd=” ＋ 编码_URL编码 (编码_BASE64编码 (到字节集 (pwd)), 真, 真) ＋ “&un=” ＋ 编码_URL编码 (user, , 真)
                Method = "POST",
            };
            HttpHelper http = new HttpHelper();
            HttpResult res = http.GetHtml(item);
            Console.WriteLine(res.Html);
            return string.Empty;
        }

        /// <summary>
        /// 判断链接是否有效
        /// </summary>
        /// <param name="sh"></param>
        /// <returns></returns>
        public static ShortInfo? IsShortUse(string sh)
        {
            HttpItem item = new HttpItem
            {
                URL = string.Format("http://pan.baidu.com/mbox/group/getinfooutauth?from_referrer=%2F&short={0}&bdstoken=undefined&channel=chunlei&web=1&app_id=250528&logid==&clienttype=0",sh),

                Cookie = "BDUSS=3laSkpCRnl4eUpFNlRpdFhCNDlPczZYSW9sd1NIR00tcEZoSVEzei00RG1yM2RYQVFBQUFBJCQAAAAAAAAAAAEAAADaa7w20fS54rXEd3JnMTIzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOYiUFfmIlBXY; STOKEN=4059bf91d477a89fee896788afc2018c9563f0e261d2c7962c8e1693af0a0d88",
            };
            HttpHelper http = new HttpHelper();
            HttpResult res = http.GetHtml(item);
            //Console.WriteLine(res.Header.ToString());
            //{"errno":112,"request_id":2267985544358739954}
            /*
            //{"errno":0,"request_id":2627978829800428627,"records":[{"gid":"142753546004176188",
            //"name":"\u6b27\u7f8e\u7684\u53ef\u4ee5\u79c1\u804a\u4e92\u6362","gdesc":"",
            //"announce":"","type":"1","status":"1","ctime":"1461345825","name_flag":"1","vip":"0",
            //"spam_count":"1","photoinfo":[{"uk":3662444496,"uname":"AUVfight",
            //"photo":"http:\/\/himg.bdimg.com\/sys\/portrait\/item\/39da0f48.jpg"},
            //{ "uk":4182698930,"uname":"\u98ce\u5439\u7a3b\u82b1\u9999136","photo":"http:\/\/himg.bdimg.com\/sys\/portrait\/item\/a5f96d4a.jpg"},
            //{ "uk":693491236,"uname":"\u98de\u82b1\u4e71\u6f2b\u5929","photo":"http:\/\/himg.bdimg.com\/sys\/portrait\/item\/9829fb51.jpg"},
            //{ "uk":1734390908,"uname":"\u77ed\u53d1\u53d8\u957f\u53d1963","photo":"http:\/\/himg.bdimg.com\/sys\/portrait\/item\/fa67a364.jpg"},
            //{ "uk":4269785236,"uname":"\u5c31\u5f97\u600e\u6837\u561b","photo":"http:\/\/himg.bdimg.com\/sys\/portrait\/item\/8efe4b7b.jpg"}],
            //"uname":"\u98de\u82b1\u4e71\u6f2b\u5929","uk":693491236,"avatar_url":"http:\/\/himg.bdimg.com\/sys\/portrait\/item\/9829fb51.jpg",
            //"group_status":"1","gtype":"1","usercount":31}],"exist":0,"timestamp":1461367584}
            */
            //Console.WriteLine(res.Html);
            Match m = Regex.Match(res.Html, "{\"errno\":0,.*?\"name\":\"(.*?)\",.*\"usercount\":(.*?)}");
            if (m.Success)
            {
                ShortInfo s = new ShortInfo();
                s.shortUrl = sh;
                s.name = StringHelper.Decode(m.Groups[1].Value);
                s.usercount = m.Groups[2].Value;

                return s;
            }
            else
            {
                Console.WriteLine($"{res.Html.Trim()}, {sh}");
                return null;
            }

            /** ERRCODE
            n={
                  0: "成功",
                  "-1": "用户名和密码验证失败",
                  "-3": "用户未激活（调用init接口）",
                  "-4": "COOKIE中未找到host_key&user_key（或BDUSS）",
                  "-6": "登录失败，请重新登录",
                  "-8": "文件已存在，不用转给自己啦",
                  "-10": t,
                  "-20": "获取验证码失败",
                  "-33": "操作的文件过多，请减少文件后重试",
                  "-60": "群成员超过上限",
                  "-66": "系统繁忙，请稍候再试",
                  "-73": "创建群个数超过上限",
                  "-80": "朋友虽好，可别贪多。明天再来搜吧",
                  1: "服务器错误",
                  2: "参数错误",
                  3: "保存文件数超限，减点试试吧",
                  12: "文件保存失败，请稍候重试",
                  111: "当前有一个保存任务正在进行，请稍候保存",
                  112: "该邀请链接失效",
                  113: "该邀请链接无效",
                  114: "任务不存在，请稍候再试",
                  2100: "用户都已经被添加过",
                  2101: "你已达到创建2000群上限",
                  2102: "群组不存在",
                  2103: "用户不在该群",
                  2107: "用户没有权限",
                  2110: "退出群组失败，请稍候重试",
                  2113: "超出10个字的限制啦",
                  2117: "好友超出限制了",
                  2118: "已经是好友",
                  2119: "群成员超过上限，请重新选择",
                  2125: "消息长度不能超过2000个字符",
                  2126: "消息中含有敏感词",
                  2131: "文件已经被删除",
                  2135: "对方拒绝接收消息",
                  2136: "对方拒绝接收消息",
                  2137: "对方拒绝接收消息",
                  2149: "操作分享超过上限了哦！",
                  2150: "每分钟抽奖超过上限了哦！",
                  2151: "啊哦，没钱了哦！",
                  2152: "您还没有完成该任务哦！"
              },
              s={
                  0: "成功",
                  "-1": "由于您分享了违反相关法律法规的文件，分享功能已被禁用，之前分享出去的文件不受影响。",
                  "-2": "用户不存在,请刷新页面后重试",
                  "-3": "文件不存在,请刷新页面后重试",
                  "-4": "登录信息有误，请重新登录试试",
                  "-5": "host_key和user_key无效",
                  "-6": "请重新登录",
                  "-7": "该分享已删除或已取消",
                  "-8": "该分享已经过期",
                  "-9": "访问密码错误",
                  "-10": "分享外链已经达到最大上限100000条，不能再次分享",
                  "-11": "验证cookie无效",
                  "-14": "对不起，短信分享每天限制20条，你今天已经分享完，请明天再来分享吧！",
                  "-15": "对不起，邮件分享每天限制20封，你今天已经分享完，请明天再来分享吧！",
                  "-16": "对不起，该文件已经限制分享！",
                  "-17": "文件分享超过限制",
                  "-30": "文件已存在",
                  "-31": "文件保存失败",
                  "-33": "一次支持操作999个，减点试试吧",
                  "-32": t,
                  "-70": "你分享的文件中包含病毒或疑似病毒，为了你和他人的数据安全，换个文件分享吧",
                  2: "参数错误",
                  3: "未登录或帐号无效",
                  4: "存储好像出问题了，请稍候再试",
                  108: "文件名有敏感词，优化一下吧",
                  110: "分享次数超出限制，可以到“我的分享”中查看已分享的文件链接",
                  114: "当前任务不存在，保存失败",
                  115: "该文件禁止分享",
                  112: '页面已过期，请<ahref="javascript: window.location.reload();">刷新</a>后重试'
              },
              i={
                  36000: "网络繁忙，请稍候再试",
                  36001: "参数错误",
                  36002: "appid错误",
                  36003: "请刷新再试",
                  36004: "请重新登录",
                  36005: "用户未登录",
                  36006: "用户未激活",
                  36007: "用户未授权",
                  36008: "用户不存在",
                  36009: "用户空间不足",
                  36010: "文件不存在",
                  36012: "操作超时，请重试",
                  36013: "同时下载的任务过多，不能下载",
                  36014: "存储路径已使用",
                  36016: "任务已删除",
                  36017: "任务已完成",
                  36018: "解析失败，种子文件损坏",
                  36019: "任务正在处理中",
                  36020: "任务地址不存在",
                  36021: "普通用户最多同时下载1个任务哦！马上开通离线下载套餐，立即下载更多！",
                  36022: "同时下载的任务过多，不能下载",
                  36023: "普通用户每月只能离线下载5个任务哦！马上开通离线下载套餐，立即下载更多！",
                  36024: "本月下载数已超限制",
                  36025: "分享链接已失效",
                  36026: "链接格式有误",
                  36027: "链接格式有误",
                  36028: "暂时无法找到相关种子信息",
                  36031: "网络繁忙，请稍候再试",
                  36032: "离线文件因含有违规内容被系统屏蔽无法下载",
                  "-19": "请输入验证码"
              }
            **/
        }

        /// <summary>
        /// 获取用户名
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns>成功返回用户名，失败返回空</returns>
        public static string GetUsername(string cookie)
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem
            {
                URL = "http://i.baidu.com/",
                Cookie = cookie,
            };
            HttpResult res = http.GetHtml(item);
            //Console.WriteLine(res.Html);
            Match m = Regex.Match(res.Html, "class=\"ibx-uc-nick\">(.*)</a>");
            if (m.Success) return m.Groups[1].Value;
            return string.Empty;
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static bool LoginOut(string cookie)
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem
            {
                URL = "http://passport.baidu.com/?logout&u=http://i.baidu.com/welcome/",
                Cookie = cookie,
            };
            HttpResult res = http.GetHtml(item);
            return (!string.IsNullOrEmpty(res.Header.Get("Location")));
        }

        private static string _GetCid()
        {
            Random r = new Random();
            int[] s = new int[4];
            s[0] = r.Next(10000, 99999);
            s[1] = r.Next(1000, 9999);
            s[2] = r.Next(1000, 9999);
            s[3] = r.Next(100, 999);
            string txt = "wappc_";
            for (int i = 0; i < 3; i++)
            {
                txt += s[i].ToString();
            }
            txt += "_" + s[3].ToString();
            Console.WriteLine(txt);
            return txt;
        }

        private static string _GetSign(string body)
        {
            string ret = HttpUtility.UrlDecode(body).Replace("&", "") + "tiebaclient!!!";
            //md5
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = System.Text.Encoding.UTF8.GetBytes(ret);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String += targetData[i].ToString("x");
            }

            ret = byte2String.ToUpper();
            return ret;
        }
    }
}